<template>
    <div class="flowStep">
        <div style="width: 50%;margin: 0 auto">
            <el-steps
                :active="activeIndex"
                finish-status="success"
                align-center
            >
                <el-step v-for="item in flowNodeList" :title="item.name" :status="item.stepStatus" :description="item.assignee"/>
            </el-steps>
        </div>
    </div>

    <el-form label-width="10%" :style="formCols" style="margin-top: 30px">
        <el-form-item v-for="(item, index) in formBuildList" :label="item.labelName">
            <component :is="components[item.component]" :isEdit="false" :isDisable="true" :properties="item" :formBuildList="formBuildList"/>
        </el-form-item>
    </el-form>

    <div class="formSubmitButton">
        <el-button @click="cancelHistoryFlow()">取消</el-button>
    </div>

    <el-collapse class="taskListClass" accordion>
        <el-collapse-item name="审批历史">
            <template #title>
                <span style="font-size: 18px; color: #037cde; margin-right: 20px">审批历史</span>
            </template>
            <el-table
                :data="taskInfoList"
                style="width: 100%; margin-bottom: 20px; margin-top: 20px;"
                row-key="id"
                :show-overflow-tooltip="true"
                class="tableContainer"
                max-height="70vh"
            >
                <el-table-column prop="flowNodeId" label="流程结点ID" />
                <el-table-column prop="assignee" label="操作人" />
                <el-table-column prop="status" label="执行状态" >
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.status === `RUNNING`">审批中</el-tag>
                        <el-tag type="success" v-if="scope.row.status === `FINISH`">审批完成</el-tag>
                        <el-tag type="success" v-if="scope.row.status === `START`">执行完成</el-tag>
                        <el-tag type="success" v-if="scope.row.status === `END`">执行结束</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="taskResult" label="审批结果" >
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.taskResult === `agree`">同意</el-tag>
                        <el-tag type="danger" v-if="scope.row.taskResult === `reject`">拒绝</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="taskContent" label="审批说明" />
                <el-table-column prop="createDate" label="任务开始时间" />
                <el-table-column prop="updateDate" label="任务结束时间" />
            </el-table>

        </el-collapse-item>
    </el-collapse>
</template>

<script name="HistoryFlowInstance" setup>
import {queryHistoryInstanceDetail, queryTaskList} from "@/request/flow";
import {computed, ref} from "vue";
import {useRoute} from "vue-router";
import YwuFormInput from "@/views/bpmn/form/component/YwuFormInput.vue";
import YwuFormSelect from "@/views/bpmn/form/component/YwuFormSelect.vue";
import YwuFormCascaderSelect from "@/views/bpmn/form/component/YwuFormCascaderSelect.vue";
import YwuFormCheckBox from "@/views/bpmn/form/component/YwuFormCheckBox.vue";
import YwuFormDate from "@/views/bpmn/form/component/YwuFormDate.vue";
import YwuFormInputNumber from "@/views/bpmn/form/component/YwuFormInputNumber.vue";
import YwuFormRadio from "@/views/bpmn/form/component/YwuFormRadio.vue";
import YwuFormRate from "@/views/bpmn/form/component/YwuFormRate.vue";
import YwuFormSwitch from "@/views/bpmn/form/component/YwuFormSwitch.vue";
import YwuFormTime from "@/views/bpmn/form/component/YwuFormTime.vue";
import YwuFormTreeSelect from "@/views/bpmn/form/component/YwuFormTreeSelect.vue";
import YwuFormUploadFile from "@/views/bpmn/form/component/YwuFormUploadFile.vue";
import YwuFormUploadImage from "@/views/bpmn/form/component/YwuFormUploadImage.vue";

// 显式声明组件变量（确保被引用）
const components = { YwuFormInput, YwuFormSelect, YwuFormCascaderSelect, YwuFormCheckBox, YwuFormDate,
    YwuFormInputNumber, YwuFormRadio, YwuFormRate, YwuFormSwitch, YwuFormTime, YwuFormTreeSelect, YwuFormUploadFile, YwuFormUploadImage };


let route = useRoute();

let globalProperties = ref({
    colNum: 1
});
let formBuildList = ref([]);
let taskId = ref("");
let activeIndex = ref(1);
let flowNodeList = ref([]);
let taskInfoList = ref([]);

function cancelHistoryFlow() {
    // 关闭当前窗口
    window.close();
}

let formCols = computed(() => {
    let res = "display: grid;gap: 16px;"
    let repeat = `grid-template-columns: repeat(${globalProperties.value.colNum}, 1fr);`
    return res + repeat;
})

init();
function init() {
    // 查询流程详情
    let id = route.query.id;
    queryHistoryInstanceDetail({id: id}).then(res => {
        if (res.code === "200") {
            let formJson = res.data.formJson
            // 序列化json
            let jsonInfo = JSON.parse(formJson);
            globalProperties.value = jsonInfo.globalProperties
            formBuildList.value = jsonInfo.componentJson
            let formInstance = JSON.parse(res.data.formInstanceJson);
            // 将实例的值填入到表单bindValue中
            for (let index = 0; index < formBuildList.value.length; index++) {
                let item = formBuildList.value[index];
                for (let i = 0; i < formInstance.length; i++) {
                    if (item.code === formInstance[i].code) {
                        item.bindValue = formInstance[i].value;
                        break;
                    }
                }
            }
            taskId.value = res.data.taskId;
            // 查询当前流程实例的任务列表
            let taskListParam = {
                id: id
            }
            let rejectLastFlag = false
            queryTaskList(taskListParam).then(taskListRes => {
                let taskList = taskListRes.data;
                taskInfoList.value = taskList;
                // 解析表单结点
                let flowJson = JSON.parse(res.data.flowJson);
                flowNodeList.value.push(flowJson);
                flowJson.stepStatus = "success";
                flowJson.assignee = res.data.startBy;
                let index = 1;
                while ("next" in flowJson && flowJson.next !== null) {
                    for (let i = 0; i < taskList.length; i++) {
                        if (flowJson.next.id === taskList[i].flowNodeId) {
                            flowJson.next.assignee = taskList[i].assignee;
                            break;
                        }
                    }
                    // 如果当前流程已经被拒绝了，那么当前的激活位置与其他情况不同
                    if (res.data.status === "REJECT_FINISH") {
                        // 取最后一个task结点的id，其所处的位置就是activeIndex
                        let lastTask = taskList[taskList.length - 1]
                        let lastTaskIdNodeId = lastTask.flowNodeId
                        if (lastTaskIdNodeId === flowJson.next.id) {
                            activeIndex.value = index + 1;
                            flowJson.next.stepStatus = "error";
                            rejectLastFlag = true
                        } else {
                            if (rejectLastFlag) {
                                flowJson.next.stepStatus = "info";
                            } else {
                                flowJson.next.stepStatus = "success";
                            }
                        }
                    } else {
                        // 计算当前的活跃结点
                        if (res.data.currentNode === flowJson.next.id) {
                            if (res.data.currentNode === "nid-end") {
                                activeIndex.value = index + 1;
                            } else {
                                activeIndex.value = index;
                            }
                        }
                        flowJson.next.stepStatus = "success";
                    }
                    flowNodeList.value.push(flowJson.next);
                    flowJson = flowJson.next
                    index++;
                }
                // 给task任务列表添加发起人结点
                let startByTask = {
                    flowNodeId: "nid-start",
                    status: "START",
                    assignee: res.data.startBy,
                    createDate: res.data.createDate,
                    updateDate: res.data.createDate,
                }
                taskInfoList.value.unshift(startByTask);
                if (res.data.status === "FINISH") {
                    let endByTask = {
                        flowNodeId: "nid-end",
                        status: "END",
                        createDate: res.data.updateDate,
                        updateDate: res.data.updateDate,
                    }
                    taskInfoList.value.push(endByTask);
                }
                for (let i = 0; i < taskInfoList.value.length; i++) {
                    if (taskInfoList.value[i].status === "RUNNING") {
                        taskInfoList.value[i].updateDate = "";
                    }
                }
            })
        }
    })
}
</script>

<style scoped lang="less">
.formSubmitButton {
    margin-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.flowStep {
    margin-top: 30px;
    margin-bottom: 60px;
}

.el-steps {
    width: 100%;
}

.taskListClass {
    margin-top: 60px;
    margin-left: 20px;
}
</style>